<template>
  <div style="display: flex">
    <el-container>
      <el-header>
        <div class="report_header" ref="headerHeight">
          <div class="report_header_left"></div>
          <div style="width: 300px;display: flex;align-items: center;margin-left: 10px;">
            <svg-icon class="primary" :icon-class="$route.meta.icon"/>
            <span style="margin-left: 5px;" class="primary">{{$route.meta.title}}</span>
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
            <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px">
              <div class="report_header_query" v-if="mchType==0||mchType==3">
                <el-select v-model="query.sysMchId" clearable placeholder="请选择商户" style="margin-left:20px" filterable
                  value-key="id" :filter-method="querySysmch" @change="changeSysMch">
                  <el-option v-for="item in mchIdOptions" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div class="report_header_query">
                <el-input prefix-icon="el-icon-search" placeholder="请输入品牌名" v-model="query.name"></el-input>
              </div>
            </div>
            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="queryClick">查询</el-button>
            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"
              v-permission="['brand.add']">新增</el-button>
          </div>
        </div>
      </el-header>
      <div class="pd10">
        
        <el-table :data="brandData" border stripe v-loadMore="[payLoads,'brand-list']" :height="curHeight" @sort-change="sortChange"
          ref="table" style="width: 100%;">
          <el-table-column type="index" label="序号" width="50" align="center" fixed>
          </el-table-column>
          <el-table-column label="缩略图" align="center" prop="logo" width="80">
            <template slot-scope="scope">
              <img :src="scope.row.logo" style="width: 50px; vertical-align:middle; overflow: hidden;">
            </template>
          </el-table-column>
          <el-table-column label="品牌" align="left" prop="name">
          </el-table-column>
          <el-table-column label="排序" align="center" width="80" prop="orders">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.orders" @blur="bulrOrders(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="80">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="编辑" v-permission="['brand.edit']" placement="top-start">
                <a @click="editClick(scope.row)">
                  <i style="color: #409EFF" class="el-icon-edit"></i>
                </a>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" v-permission="['brand.del']" placement="top-start">
                <a style="margin-left: 10px" @click="deleteBrand(scope.row)">
                  <i style="color: #F56C6C" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadBrand"></pagination>
      </el-footer>
    </el-container>
  </div>
</template>
<script>
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import {
    list as sysMchList,
    getInfo
  } from '@/api/sysMch'
  import {
    list,
    del,
    update
  } from '@/api/brand'
  import utils from '../../utils/utils.js'
  import {
    EventBus
  } from '@/api/eventBus'
  import Pagination from '@/components/Pagination';
  import loadMore from '@/utils/loadMore.js'
  export default {
    name: 'brand-list',
    directives: {
      permission,
      loadMore
    },
    data() {
      return {
        brandData: [],
        mchType: '',
        pageNum: 1,
        mchIdOptions: [],
        pageSize: 20,
        total: 0,
        queryType: true,
        query: {
          sysMchId: '',
          name: '',
        },
        keyword: {
          sysMchId: '',
          name: '',
        },
        curHeight: null,
        excelData: [],
        direction: '',
        sortField: '',
        payLoads: '',
        sorting: {
          id: '',
          orders: ''
        },
      }
    },
    components: {
      Pagination
    },
    created() {
      var _this = this
      this.loadBrand()
      this.loadSysmch('')
      this.loadMch()
      EventBus.$on('brand-add', res => { // 监听新增完毕
        // 更新列表数组
        _this.brandData.splice(0, 0, res)
      });
      EventBus.$on('brand-edit', res => { // 监听新增完毕
        // 更新列表数组
        for (let i = 0; i < _this.brandData.length; i++) {
          if (_this.brandData[i].id == res.id) {
            this.$set(this.brandData, i, res)
          }
        }
      })
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    filters: {

    },
    activated() {
      this.payLoads = new Date().getTime();
    },
    methods: {
      loadSysmch(query) {
        sysMchList({
          name: query
        }).then(res => {
          this.mchIdOptions = res.data.data.filter(val => {
            return val.mchType === 3 || val.mchType === 1
          })
        }).catch(err => {
          console.log(err)
        })
      },
      changeSysMch() {
        this.loadBrand()
      },
      querySysmch(query) {
        this.loadSysmch(query)
      },
      loadMch() {
        getInfo().then(res => {
          this.mchType = res.data.mchType
        })
      },
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            if (this.queryType == false) {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 266 //减去页面上固定高度height
            } else {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 220 //减去页面上固定高度height
            }
          })();
        };
      },
      comeIn() {
        var h = document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220 //减去页面上固定高度height
      },
      editClick(row) {
        this.$router.push({
          path: '/brand/edit',
          query: {
            id: row.id
          }
        })
      },
      loadBrand() {
        var _this = this
        let params = new URLSearchParams();
        params.append('pageNum', _this.pageNum);
        params.append('pageSize', _this.pageSize);
        params.append('mchId', _this.query.sysMchId)
        params.append('name', _this.keyword.name);
        params.append('sortField', _this.sortField);
        params.append('direction', _this.direction);
        list(params).then(response => {
          console.log(response)
          _this.brandData = response.data.data
          _this.total = response.data.total
        }).catch(error => {
          console.log('error!!')
        });
      },

      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == false) {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 266 //减去页面上固定高度height
        } else {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 220 //减去页面上固定高度height
        }
      },
      addClick() {
        this.$router.push({
          path: '/brand/add'
        })
      },
      deleteBrand(data) {
        console.log(data)
        var _this = this
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(data.id).then(response => {
            console.log(response)
            if (response.type)
              // 更新列表数组
              _this.brandData.forEach(function(item, index) {
                if (item.id == data.id) {
                  _this.brandData.splice(index, 1)
                }
              })
          }).catch(error => {
            console.log('error!!')
          });
        }).catch(() => {});
      },
      queryClick() {
        this.keyword = this.query;
        this.pageNum = 1
        this.loadBrand()
      },
      resetClick() {
        this.query.name = '';
        this.keyword = this.query;
        this.pageNum = 1;
        this.loadBrand()
      },
      //      handleDownload() {
      //        this.prepareExcel()
      //        import('@/vendor/Export2Excel').then(excel => {
      //          const tHeader = ["序号", "姓名", "电话", "备用电话", "地址", "邮箱", "性别", "生日", "等级", "可用余额", "冻结余额", "金币积分"];
      //          const filterVal = ["index", "name", "mobile", "phone", "areaName", "email", "gender", "birth", "vip", "balance", "freezeBalance", "point"];
      //          const list = this.excelData
      //          const data = this.formatJson(filterVal, list)
      //          excel.export_json_to_excel({
      //            header: tHeader,
      //            data,
      //            filename: this.filename,
      //            autoWidth: this.autoWidth,
      //            bookType: this.bookType
      //          })
      //        })
      //      },
      //      prepareExcel() {
      //        var _this = this
      //        let params = new URLSearchParams();
      //        params.append('pageNum', 1);
      //        params.append('pageSize', 10000);
      //        params.append('title',_this.keyword.title);
      //        params.append('subTitle',_this.keyword.subTitle)
      //        params.append('mchGaugeGategoryId', _this.mchGaugeGategoryId);
      //        params.append('deleted', _this.deleted);
      //        list(params).then(response => {
      //          let ex = {};
      //          for (var i = 0; i < response.data.data.length; i++) {
      //            ex = {
      //              index: i,
      //              name: response.data.data[i].name,
      //              mobile: response.data.data[i].mobile,
      //              phone: response.data.data[i].phone,
      //              areaName: response.data.data[i].areaName + response.data.data[i].address,
      //              email: response.data.data[i].email,
      //              gender: response.data.data[i].gender,
      //              birth: response.data.data[i].birth,
      //              vip: response.data.data[i].vip,
      //              balance: response.data.data[i].balance,
      //              freezeBalance: response.data.data[i].freezeBalance,
      //              point: response.data.data[i].point,
      //            };
      //            _this.excelData.push(ex)
      //          }
      //        }).catch(error => {
      //          console.log('error!!')
      //        });
      //      },
      //      formatJson(filterVal, jsonData) {
      //        return jsonData.map(v => filterVal.map(j => v[j]));
      //      },
      // 表格排序
      sortChange(column) {
        console.log(column)
        this.sortField = column.prop;
        if (column.order == 'ascending') {
          this.direction = 'asc'
        } else {
          this.direction = 'desc'
        }
        this.loadBrand()
      },
      bulrOrders(data) {
        console.log(data)
        this.sorting.id = data.id;
        this.sorting.orders = data.orders;
        this.saveSorting();
      },
      saveSorting() {
        var _this = this
        update(_this.sorting).then(response => {
          console.log(response)
          _this.brandData.forEach(function(item) {
            if (item.id == response.data.id) {
              item.orders = response.data.orders
            }
          });
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          });
        }).catch(error => {
          console.log(error)
        });
      },
    }
  }
</script>

<style scoped>
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #f2f2f2;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }
.report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
</style>
